package com.bkgy.controller.planking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.commom.model.Temp;
import com.bkgy.controller.planking.dao.PdoL3Cgl1870Mapper;
import com.bkgy.controller.planking.dao.PlanKing1870Dao;
import com.bkgy.controller.planking.dao.TBProfit1870Dao;
import com.bkgy.controller.planking.entity.*;
import com.bkgy.controller.planking.entity.dto.PlanKingTwoHour;
import com.bkgy.controller.planking.entity.dto.PlanKingTwoHourBase;
import com.bkgy.controller.planking.entity.dto.TPdi1870Code;
import com.bkgy.controller.planking.entity.dto.TPdi1870Home;
import com.bkgy.controller.planking.service.ITPdiCodeService;
import com.bkgy.controller.planking.service.ITPdiHomeService;
import com.bkgy.controller.planking.service.ITbProfit1870Service;
import com.bkgy.controller.planking.service.PlanKing1870Service;
import com.bkgy.controller.planking.util.ProfitUtil;
import com.bkgy.controller.technology.entity.TDefectData;
import com.bkgy.controller.technology.service.ITDefectDataService;
import com.bkgy.sys.common.constant.CommonConstant;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.DateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 镀锌外板服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PlanKing1870ServiceImpl extends ServiceImpl<PlanKing1870Dao, TbProfit1870Par> implements PlanKing1870Service {
    private final PlanKing1870Dao dao;
    private final TBProfit1870Dao profitDao;
    private final PdoL3Cgl1870Mapper l3Cgl1870Mapper;
    private final ITbProfit1870Service profitService;
    private final ITPdiCodeService pdiCodeService;
    private final ITPdiHomeService pdiHomeService;
    private final ITDefectDataService defectService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData<String> buildTbProfit1870(String begingDate) {
        profitService.removeAfterDate(begingDate);
        //映射成一对多，方便计算
        List<TbProfit1870Par> list = dao.loadBaseDate(begingDate.replaceAll("-", ""), null);
        //查询缺陷（注意此表数据有重复）
        LambdaQueryWrapper<TDefectData> w = new LambdaQueryWrapper();
        Map<String, String> defectMap = new HashMap<>();
        Date d = DateUtil.getStringToDate("yyyy-MM-dd", begingDate);
        w.ge(TDefectData::getCreateTime, d).orderByAsc(TDefectData::getCreateTime);
        List<TDefectData> defectList = defectService.list(w);
        for (TDefectData defectData : defectList) {
            defectMap.put(defectData.getExtId(), defectData.getDefectClass1());
        }

        for (TbProfit1870Par par : list) {
            for (TbProfit1870Sub sub : par.getSubList()) {
                if (defectMap.containsKey(sub.getExtid())) {
                    sub.setDefectLevel(defectMap.get(sub.getExtid()));
                }
            }
        }
        dealData(list, begingDate);
        return ResultData.ResultDataSuccess("success");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealData(List<TbProfit1870Par> list, String timeLevel) {
        LambdaQueryWrapper<TbProfit1870> wrapper = new LambdaQueryWrapper();
        wrapper.ge(TbProfit1870::getCredate, timeLevel);
        int num = profitDao.delete(wrapper);
        log.info("删除≥出口卷时间{} 的{}条记录", timeLevel, num);

        //上一分卷出口时间。
        Date lastExtEndTime = null;
        //获得上一整卷最后分卷的出口时间
        String entid = null;
        if (list.size() > 0) {
            entid = list.get(0).getEntid();
        }
        TbProfit1870 tbProfit1870 = profitService.selectTopRecord(entid);
        if (tbProfit1870 != null) {
            lastExtEndTime = DateUtil.getStringToDate("yyyyMMddHHmmss", tbProfit1870.getCredate());
        }
        //初始化时间原点
        if (lastExtEndTime == null && list != null && !list.isEmpty()) {
            TbProfit1870Par boo = list.get(0);
            lastExtEndTime = DateUtil.getStringToDate("yyyyMMdd", boo.getSubList().get(0).getCredate().substring(0, 8));
        }

        for (TbProfit1870Par item : list) {
            //出口重量和
            BigDecimal sumOutputWeight = BigDecimal.ZERO;
            //上一轧卷彻底结束时间
            Date lastItemDate = lastExtEndTime;
            //历史机时产量
            for (TbProfit1870Sub sub : item.getSubList()) {
                Date currentEndTime = DateUtil.getStringToDate("yyyyMMddHHmmss", sub.getCredate());
                long diff = currentEndTime.getTime() - lastExtEndTime.getTime();
                long l = diff / 1000;
                sub.setProdSec(l > 1800 ? "1800" : (l + ""));
                //出口千克数*3600/毫秒差
                BigDecimal outputHour = sub.getExtWeight().multiply(BigDecimal.valueOf(3600)).divide(BigDecimal.valueOf(diff), 4, BigDecimal.ROUND_HALF_UP);
                sub.setOutputHour(outputHour);

                sumOutputWeight = sumOutputWeight.add(sub.getExtWeight());
                lastExtEndTime = currentEndTime;
            }
            //成材率
            item.setYeild(sumOutputWeight.divide(item.getMweight(), 4, BigDecimal.ROUND_HALF_UP));
            //入口机时产量
            BigDecimal inputHour = item.getMweight().multiply(BigDecimal.valueOf(3600)).divide(BigDecimal.valueOf(lastExtEndTime.getTime() - lastItemDate.getTime()), 4, BigDecimal.ROUND_HALF_UP);
            item.setInputHour(inputHour);
        }

        //上月各指标大于0的出口重量和
        String startTime = DateUtil.lastMonthFirstDay("yyyyMM01");
        String endTime = DateUtil.thisMonthFirstDay("yyyyMMdd");
        BigDecimal pressAirWt = dao.lastMonthOutputPressAir(startTime, endTime);
        BigDecimal steamWt = dao.lastMonthOutputSteam(startTime, endTime);
        BigDecimal saltWt = dao.lastMonthOutputSalt(startTime, endTime);
        BigDecimal fineNitrogenWt = dao.lastMonthOutputFine(startTime, endTime);
        BigDecimal roughNitrogenWt = dao.lastMonthOutputRough(startTime, endTime);
        BigDecimal cleanWaterWt = dao.lastMonthOutputWater(startTime, endTime);
        BigDecimal hydrogenWt = dao.lastMonthOutputHy(startTime, endTime);

        String d1 = DateUtil.lastMonthFirstDay("yyyy-MM-01");
        String d2 = DateUtil.thisMonthFirstDay("yyyy-MM-dd");
        //上月总出口量（T_PDO_DATA）
        BigDecimal lastMonthOutputWeight = dao.lastMonthOutput(d1, d2);

        //对应指标大于0的钢出口重量
        if (pressAirWt == null || pressAirWt.compareTo(BigDecimal.ZERO) == 0) {
            pressAirWt = lastMonthOutputWeight;
        }
        if (steamWt == null || steamWt.compareTo(BigDecimal.ZERO) == 0) {
            steamWt = lastMonthOutputWeight;
        }
        if (saltWt == null || saltWt.compareTo(BigDecimal.ZERO) == 0) {
            saltWt = lastMonthOutputWeight;
        }
        if (cleanWaterWt == null || cleanWaterWt.compareTo(BigDecimal.ZERO) == 0) {
            cleanWaterWt = lastMonthOutputWeight;
        }
        if (fineNitrogenWt == null || fineNitrogenWt.compareTo(BigDecimal.ZERO) == 0) {
            fineNitrogenWt = lastMonthOutputWeight;
        }
        if (roughNitrogenWt == null || roughNitrogenWt.compareTo(BigDecimal.ZERO) == 0) {
            roughNitrogenWt = lastMonthOutputWeight;
        }
        if (hydrogenWt == null || hydrogenWt.compareTo(BigDecimal.ZERO) == 0) {
            hydrogenWt = lastMonthOutputWeight;
        }

        //上月各钢种（牌号+宽度等级+厚度等级）出口量及指标
        Map<String, Temp> totalMap = new HashMap<>();
        BigDecimal sumExtWeight = BigDecimal.ZERO;//总出口重量
        BigDecimal sumGas = BigDecimal.ZERO;//总用煤气量
        List<Temp> sumList = dao.lastMonthOutputGas(startTime, endTime);
        for (Temp temp : sumList) {
            String key = temp.getK();
            sumExtWeight = sumExtWeight.add(temp.getV());
            sumGas = sumGas.add(temp.getV2());
            totalMap.put(key, temp);
        }

        //范围上限20%
        BigDecimal rate2 = BigDecimal.valueOf(1.2);
        //上月总用量，压缩空气量、蒸汽、脱盐水、精氮、粗氮、清洗段水量、氢气量，范围上浮20%
        ExcObj excObj = dao.lastTotal(d1, d2);
        BigDecimal pressAir2 = excObj.getSumAir().multiply(rate2);
        BigDecimal steam2 = excObj.getSumSteam().multiply(rate2);
        BigDecimal salt2 = excObj.getSumSalt().multiply(rate2);
        BigDecimal fineNitrogen2 = excObj.getSumFineNitrogen().multiply(rate2);
        BigDecimal roughNitrogen2 = excObj.getSumRoughNitrogen().multiply(rate2);
        BigDecimal hydrogen2 = excObj.getSumHydrogen().multiply(rate2);
        BigDecimal water2 = excObj.getSumWater().multiply(rate2);
        BigDecimal powerMount2 = BigDecimal.valueOf(68.67).multiply(rate2);
        log.info("pressAir2:{}", pressAir2);
        log.info("steam2:{}", steam2);
        log.info("salt2:{}", salt2);
        log.info("fineNitrogen2:{}", fineNitrogen2);
        log.info("roughNitrogen2:{}", roughNitrogen2);
        log.info("hydrogen2:{}", hydrogen2);
        log.info("water2:{}", water2);
        log.info("powerMount2:{}", powerMount2);

        //查询吨钢收益
        Map<String, List<BigDecimal>> tonMap = new HashMap<>();
        BigDecimal sumBenifit = BigDecimal.ZERO;
        List<Temp> tonList = dao.loadTonBenifit();
        for (Temp ton : tonList) {
            if (tonMap.containsKey(ton.getK())) {
                tonMap.get(ton.getK()).add(ton.getV());
            } else {
                List<BigDecimal> tempList = new ArrayList<>();
                tempList.add(ton.getV());
                tonMap.put(ton.getK(), tempList);
            }
            sumBenifit = sumBenifit.add(ton.getV());
        }

        List<TbProfit1870> proList = new ArrayList<>();
        for (TbProfit1870Par item : list) {
            for (TbProfit1870Sub sub : item.getSubList()) {
                TbProfit1870 pro = new TbProfit1870();
                pro.setExtid(sub.getExtid());
                pro.setEntid(sub.getEntid());
                pro.setMwidth(item.getMwidth());
                pro.setMthick(item.getMthick());
                pro.setMweight(item.getMweight());
                pro.setNTargcoatthkupsur(item.getNTargcoatthkupsur());
                pro.setInputHour(item.getInputHour());
                pro.setYeild(item.getYeild());
                pro.setSteelgrade(sub.getSteelgrade());
                pro.setSurfacecode(sub.getSurfacecode());
                pro.setExtThick(sub.getExtThick());
                pro.setThickClass(ProfitUtil.getThickGrade(sub.getExtThick()));
                pro.setExtWidth(sub.getExtWidth());
                pro.setWidthClass(ProfitUtil.getWidthGrade(sub.getExtWidth()));
                pro.setDefectLevel(sub.getDefectLevel());
                BigDecimal tonProfit = BigDecimal.ZERO;
                String k = pro.getSteelgrade() + pro.getThickClass() + pro.getWidthClass();
                if (tonMap.containsKey(k)) {
                    for (BigDecimal b : tonMap.get(k)) {
                        tonProfit = tonProfit.add(b);
                    }
                    tonProfit = tonProfit.divide(BigDecimal.valueOf(tonMap.get(k).size()), 4, BigDecimal.ROUND_HALF_UP);
                } else {
                    tonProfit = sumBenifit.divide(BigDecimal.valueOf(tonList.size()), 4, BigDecimal.ROUND_HALF_UP);
                }
                //根据缺陷码判定等级，调整吨钢效益。00废品2280元，20可利用材料1880元，10降级品是600元
                if (StringUtils.isNotEmpty(sub.getDefectLevel())) {
                    if ("00".equals(sub.getDefectLevel()) || "0".equals(sub.getDefectLevel())) {
                        tonProfit = tonProfit.subtract(BigDecimal.valueOf(2280));
                    } else if ("10".equals(sub.getDefectLevel())) {
                        tonProfit = tonProfit.subtract(BigDecimal.valueOf(600));
                    } else if ("20".equals(sub.getDefectLevel())) {
                        tonProfit = tonProfit.subtract(BigDecimal.valueOf(1880));
                    }
                }
                pro.setTonProfit(tonProfit);
                //1000*10000
                pro.setTonProfitTotal(sub.getExtWeight().multiply(tonProfit).divide(BigDecimal.valueOf(10000000), 4, BigDecimal.ROUND_HALF_UP));

                pro.setExtWeight(sub.getExtWeight());
                pro.setCredate(sub.getCredate());
                pro.setProdSec(sub.getProdSec());
                pro.setOutputHour(sub.getOutputHour());
                pro.setNOilamount(sub.getNOilamount());
                pro.setTurnl2(sub.getTurnl2());
                pro.setPressAir(sub.getPressAir());
                if (sub.getPressAir() != null) {
                    Integer flag = 0;
                    BigDecimal c = pressAirWt.multiply(sub.getPressAir()).divide(sub.getExtWeight(), 4, BigDecimal.ROUND_HALF_UP);
                    if (c.compareTo(pressAir2) > 0) {
                        flag = 1;
                    }
                    pro.setPressAirExc(flag);
                }
                pro.setSteam(sub.getSteam());

                if (sub.getSteam() != null) {
                    Integer flag = 0;
                    BigDecimal c = steamWt.multiply(sub.getSteam()).divide(sub.getExtWeight(), 4, BigDecimal.ROUND_HALF_UP);
                    if (c.compareTo(steam2) > 0) {
                        flag = 1;
                    }
                    pro.setSteamExc(flag);
                }
                pro.setSalt(sub.getSalt());
                if (sub.getSalt() != null) {
                    Integer flag = 0;
                    BigDecimal c = saltWt.multiply(sub.getSalt()).divide(sub.getExtWeight(), 4, BigDecimal.ROUND_HALF_UP);
                    if (c.compareTo(salt2) > 0) {
                        flag = 1;
                    }
                    pro.setSaltExc(flag);
                }
                pro.setGas(sub.getGas());
                if (sub.getGas() != null) {
                    Integer flag = 0;
                    BigDecimal totalExtWeightGas = sumExtWeight;
                    BigDecimal totalGas = sumGas;
                    String key = pro.getSteelgrade() + pro.getWidthClass() + sub.getExtThick();
                    if (totalMap.containsKey(key)) {
                        totalExtWeightGas = totalMap.get(key).getV();
                        totalGas = totalMap.get(key).getV2();
                    }
                    BigDecimal rightLevel = totalGas.multiply(rate2);
                    BigDecimal c = sub.getGas().multiply(totalExtWeightGas).divide(sub.getExtWeight(), 4, BigDecimal.ROUND_HALF_UP);
                    if (c.compareTo(rightLevel) > 0) {
                        flag = 1;
                    }
                    pro.setGasExc(flag);
                }
                //pro.setGasExc(0);
                pro.setFineNitrogen(sub.getFineNitrogen());
                if (sub.getFineNitrogen() != null) {
                    Integer flag = 0;
                    BigDecimal c = fineNitrogenWt.multiply(sub.getFineNitrogen()).divide(sub.getExtWeight(), 4, BigDecimal.ROUND_HALF_UP);
                    if (c.compareTo(fineNitrogen2) > 0) {
                        flag = 1;
                    }
                    pro.setFineNitrogenExc(flag);
                }
                pro.setRoughNitrogen(sub.getRoughNitrogen());
                if (sub.getRoughNitrogen() != null) {
                    Integer flag = 0;
                    BigDecimal c = roughNitrogenWt.multiply(sub.getRoughNitrogen()).divide(sub.getExtWeight(), 4, BigDecimal.ROUND_HALF_UP);
                    if (c.compareTo(roughNitrogen2) > 0) {
                        flag = 1;
                    }
                    pro.setRoughNitrogenExc(flag);
                }
                pro.setCleanWater(sub.getCleanWater());
                if (sub.getCleanWater() != null) {
                    Integer flag = 0;
                    BigDecimal c = cleanWaterWt.multiply(sub.getCleanWater()).divide(sub.getExtWeight(), 4, BigDecimal.ROUND_HALF_UP);
                    if (c.compareTo(water2) > 0) {
                        flag = 1;
                    }
                    pro.setCleanWaterExc(flag);
                }
                pro.setHydrogen(sub.getHydrogen());
                if (sub.getHydrogen() != null) {
                    Integer flag = 0;
                    BigDecimal c = hydrogenWt.multiply(sub.getHydrogen()).divide(sub.getExtWeight(), 4, BigDecimal.ROUND_HALF_UP);
                    if (c.compareTo(hydrogen2) > 0) {
                        flag = 1;
                    }
                    pro.setHydrogenExc(flag);
                }
                pro.setPowerMount(sub.getPowerMount());
                if (sub.getPowerMount() != null) {
                    Integer flag = 0;
                    BigDecimal c = sub.getPowerMount().multiply(BigDecimal.valueOf(1000)).divide(sub.getExtWeight(), 4, BigDecimal.ROUND_HALF_UP);
                    if (c.compareTo(powerMount2) > 0) {
                        flag = 1;
                    }
                    pro.setPowerMountExc(flag);
                }
                pro.setNOilamount(sub.getNOilamount());
                if (sub.getNOilamount() != null) {
                    if (sub.getNOilamount().compareTo(BigDecimal.ZERO) == 0) {
                        pro.setNOilamountExc(0);
                    }
                    if (item.getMinOil() != null) {
                        BigDecimal minOil = item.getMinOil();
                        BigDecimal maxOil = minOil.multiply(rate2);
                        Integer flag = 0;
                        if (sub.getNOilamount().compareTo(maxOil) > 0) {
                            flag = 1;
                        }
                        pro.setNOilamountExc(flag);
                    }
                }
                pro.setZinc(sub.getZinc());
                if (sub.getZinc() != null && item.getMinZinc() != null) {
                    BigDecimal minZinc = item.getMinZinc();
                    BigDecimal maxZinc = minZinc.multiply(rate2);
                    Integer flag = 0;
                    if (sub.getZinc().compareTo(maxZinc) > 0) {
                        flag = 1;
                    }
                    pro.setZincExc(flag);
                }
                proList.add(pro);
            }
        }

        log.info("批量保存 {} 条记录", proList.size());
        profitService.saveBatch(proList);
    }

    @Override
    public ResultData<PlanKingTwoHour> get1870twoHour(String startTime, String endTime) {
        Date d1;
        Date d2;
        Calendar cal = Calendar.getInstance();
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //开始结束都是空
            d2 = new Date();
            cal.setTime(d2);
            cal.add(Calendar.HOUR, -2);
            d1 = cal.getTime();
        } else if (StringUtils.isEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            //开始空，结束不空
            d2 = DateUtil.getStringToDate("yyyy-MM-dd HH:mm:ss", endTime);
            cal.setTime(d2);
            cal.add(Calendar.HOUR, -2);
            d1 = cal.getTime();
        } else if (StringUtils.isNotEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            //开始不空，结束空
            d1 = DateUtil.getStringToDate("yyyy-MM-dd HH:mm:ss", startTime);
            cal.setTime(d1);
            cal.add(Calendar.HOUR, 2);
            d2 = cal.getTime();
        } else {
            d1 = DateUtil.getStringToDate("yyyy-MM-dd HH:mm:ss", startTime);
            d2 = DateUtil.getStringToDate("yyyy-MM-dd HH:mm:ss", endTime);
        }

        startTime = DateUtil.getDateToString(d1, "yyyyMMddHHmmss");
        endTime = DateUtil.getDateToString(d2, "yyyyMMddHHmmss");
        //查询镀锌区间段的L3数据
        List<PlanKingTwoHourBase> list = dao.get1870twoHour(startTime, endTime);

        BigDecimal sumOutputWeight = BigDecimal.ZERO;
        BigDecimal sumInputWeight = BigDecimal.ZERO;
        BigDecimal sumFirstOutputWeight = BigDecimal.ZERO;
        BigDecimal sumWasteOutputWeight = BigDecimal.ZERO;//废品量
        BigDecimal sumCloseOutputWeight = BigDecimal.ZERO;
        BigDecimal sumdownOutputWeight = BigDecimal.ZERO;
        BigDecimal sumSanlengOutputWeight = BigDecimal.ZERO;//归户是三冷的总出口重
        BigDecimal sumHomeOutputWeight = BigDecimal.ZERO;//归户是三冷的合格重量
        Map<String, BigDecimal> enclosedMap = new HashMap<>();
        Map<String, BigDecimal> downMap = new HashMap<>();
        for (PlanKingTwoHourBase item : list) {
            //缺陷详情
            String defectInfo = CommonConstant.defectCodeMap.containsKey(item.getDefectCode1()) ? CommonConstant.defectCodeMap.get(item.getDefectCode1()) : item.getDefectCode1();
            //归户详情
            String attrInfo = CommonConstant.tPdi1870HomeMap.get(item.getCodeName());
            //总投入量累计
            sumInputWeight = sumInputWeight.add(item.getInMat1UseWt());
            //总出口重量累计
            sumOutputWeight = sumOutputWeight.add(item.getOutMatWt());
            //归户是三冷的出口重量
            if (attrInfo != null && attrInfo.contains("三冷") && attrInfo.indexOf("三冷") < 5) {
                sumSanlengOutputWeight = sumSanlengOutputWeight.add(item.getOutMatWt());
            }

            //订货精度与实际精度不一致认为是降级
            if (!item.getSurfaceCode().equals(item.getSurfaceAccuClassCode())) {
                sumdownOutputWeight = sumdownOutputWeight.add(item.getOutMatWt());
                if (downMap.containsKey(defectInfo)) {
                    downMap.put(defectInfo, downMap.get(defectInfo).add(item.getOutMatWt()));
                } else if(defectInfo == null){
                    downMap.put("其他", item.getOutMatWt());
                }else{
                    downMap.put(defectInfo, item.getOutMatWt());
                }
            } else {
                //未降级就是一次通过
                sumFirstOutputWeight = sumFirstOutputWeight.add(item.getOutMatWt());
                if (attrInfo != null && attrInfo.contains("三冷") && attrInfo.indexOf("三冷") < 5) {
                    sumHomeOutputWeight = sumHomeOutputWeight.add(item.getOutMatWt());
                }
            }

            //废品
            if ("00".equals(item.getSurfaceAccuClassCode())) {
                sumWasteOutputWeight = sumWasteOutputWeight.add(item.getOutMatWt());
            }

            //缺陷注释
            String comment = item.getDefectComment1();
            if (comment != null && comment.contains("封闭") && comment.indexOf("封闭") < 5) {
                //封闭出口量累计
                sumCloseOutputWeight = sumCloseOutputWeight.add(item.getOutMatWt());
                //分别累计各种封闭量不同的缺陷重量
                if (enclosedMap.containsKey(defectInfo)) {
                    enclosedMap.put(defectInfo, enclosedMap.get(defectInfo).add(item.getOutMatWt()));
                } else if(defectInfo == null){
                    enclosedMap.put("其他", item.getOutMatWt());
                }else{
                    enclosedMap.put(defectInfo, item.getOutMatWt());
                }
            }
        }

        PlanKingTwoHour obj = new PlanKingTwoHour();
        obj.setInputAmount(sumInputWeight);
        obj.setEnclosed(sumCloseOutputWeight);
        obj.setEnclosedDetail(enclosedMap);
        obj.setDowngraded(sumdownOutputWeight);
        obj.setDowngradedDetail(downMap);
        obj.setWasteAmount(sumWasteOutputWeight);
        obj.setOutputAmount(sumOutputWeight);//产出量

        //直通率=（产出量-封闭量-降级量）/产出量
        //一次合格率=一次通过的出口重量/总出口重量
        if (sumOutputWeight.compareTo(BigDecimal.ZERO) != 0) {
            //直通率
            obj.setThroughputRate(obj.getOutputAmount().subtract(obj.getEnclosed()).subtract(obj.getDowngraded())
                    .divide(obj.getOutputAmount(), 4, BigDecimal.ROUND_HALF_UP));
            //一次合格率
            obj.setFirstPassYield(sumFirstOutputWeight.divide(sumOutputWeight, 4, BigDecimal.ROUND_HALF_UP));
        }
        //内部合格率=（归户代码是三冷）合格出口重/（归户代码是三冷）总出口重量
        if (sumSanlengOutputWeight.compareTo(BigDecimal.ZERO) != 0) {
            obj.setInRate(sumHomeOutputWeight.divide(sumSanlengOutputWeight, 4, BigDecimal.ROUND_HALF_UP));
        }

        return ResultData.ResultDataSuccess(obj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData<String> importCodeParam() {
        FileInputStream in = null;
        try {
            in = new FileInputStream("D:\\workspace\\项目文档\\报表\\外板\\外板编号与名称.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();

            for (int i = 1; i <= lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                String col0 = row.getCell(0).getStringCellValue();
                String col1 = row.getCell(1).getStringCellValue();
                String col2 = row.getCell(2).getStringCellValue();
                if (StringUtils.isNotEmpty(col1)) {
                    TPdi1870Code t = new TPdi1870Code();
                    t.setDefectCode(col0);
                    t.setDefectName(col1);
                    t.setDefectClassName(col2);
                    pdiCodeService.save(t);
                }
            }
            excel.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return ResultData.ResultDataSuccess("success");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData<String> importGuihuCode() {
        FileInputStream in = null;
        try {
            in = new FileInputStream("D:\\workspace\\项目文档\\报表\\外板\\缺陷归户代码.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();

            for (int i = 1; i <= lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                String col0 = row.getCell(0).getStringCellValue();
                String col1 = row.getCell(1).getStringCellValue();
                if (StringUtils.isNotEmpty(col0) && StringUtils.isNotEmpty(col1)) {
                    TPdi1870Home t = new TPdi1870Home();
                    t.setCode(col0);
                    t.setCodeName(col1);
                    pdiHomeService.save(t);
                }
            }
            excel.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return ResultData.ResultDataSuccess("success");
    }

    @Override
    public ResultData getPlanKing1870Data(String startTime, String endTime) {
        Date d1 = DateUtil.getStringToDate("yyyy-MM-dd-HH:mm:ss.SSSSSS", startTime);
        Date d2 = DateUtil.getStringToDate("yyyyMMddHHmmss", startTime);
        startTime = DateUtil.getDateToString(d1, "yyyyMMddHHmmss");
        List<TPdoDataL3Cgl1870> list = l3Cgl1870Mapper.getPlanKing1870Data(startTime, endTime);

        startTime = DateUtil.getDateToString(d1, "yyyy-MM-dd HH:mm:ss");
        endTime = DateUtil.getDateToString(d2, "yyyy-MM-dd HH:mm:ss");
        for (TPdoDataL3Cgl1870 item : list) {
            item.setStartTime(startTime);
            item.setEndTime(endTime);
        }
        return ResultData.ResultDataSuccess(list, list.size());
    }
}
